package cn.hxzy.zyicon.service.impl;

import cn.hxzy.zyicon.entity.Icon;
import cn.hxzy.zyicon.entity.IconGroup;
import cn.hxzy.zyicon.entity.Image;
import cn.hxzy.zyicon.entity.vo.PageBean;
import cn.hxzy.zyicon.repository.ImageRepository;
import cn.hxzy.zyicon.service.ImageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Optional;

@Service("imageService")
public class ImageServiceImpl implements ImageService {
    @Autowired
    private ImageRepository imageRepository;

    @Override
    public PageBean<Image> findAll(PageBean<Image> pageBean) {
        Pageable pageable = PageRequest.of(pageBean.getPage() - 1, pageBean.getSize(), Sort.by(Sort.Order.desc("createTime")));
        Page<Image> all = imageRepository.findAll(pageable);
        pageBean.setList(all.getContent());
        pageBean.setCount(all.getTotalElements());
        pageBean.setPageCount(all.getTotalPages());
        return pageBean;
    }


    @Override
    public void save(Image image) {
        imageRepository.save(image);
    }

    @Override
    public void delete(Integer id) {
        imageRepository.deleteById(id);
    }

    @Override
    public Image findById(Integer id) {
        Optional<Image> byId = imageRepository.findById(id);
        if (byId.isPresent()) {
            return byId.get();
        }
        return null;
    }

    @Override
    public PageBean<Image> findImageByNameLike(String searchName, PageBean<Image> imagePageBean) {
        searchName = "%" + searchName + "%";
        Pageable pageable = PageRequest.of(imagePageBean.getPage() - 1, imagePageBean.getSize(), Sort.by(Sort.Order.desc("createTime")));
        Page<Image> all = imageRepository.findImageByNameLike(pageable, searchName);
        imagePageBean.setList(all.getContent());
        imagePageBean.setCount(all.getTotalElements());
        imagePageBean.setPageCount(all.getTotalPages());
        return imagePageBean;

    }

    @Override
    public void update(Image image) {
        imageRepository.save(image);
    }

    @Override
    public void add(Image image) {
        imageRepository.save(image);
    }
}
